//app.js
//创建应用程序对象
//第三方平台自定义的数据
const extConfig = wx.getExtConfigSync();
// const extConfig = {
//   apiHost: "https://wxapp.weilian.city",
//   beid: "16",
//   name: "云盈餐饮",
//   tabBarSetting: {
//     index1: {
//       id: "122743",
//       pagePath: "pages/index1/index1",
//       tplId: "15",
//       type: "custom",
//     }
//   }
// }
console.log("extConfig-------------", extConfig)
//对自定义图标进行处理,兼容之前的自定义图片，因为有自定义图片所以不能用这个判断
let tabL = extConfig['customTabBar'];
tabL.list.forEach((item, index) => {
  if (item.selectedIconPath.indexOf('imgs/tabIcon/') == -1) {
    item.isNewImg = true;
  } else {
    item.isNewImg = false;
  }
});
extConfig['customTabBar'] = tabL
App({
  API_HOST: extConfig['apiHost'],
  token: '',
  expiredTime: 0,
  pageId: 0,
  tplId: 0,
  beid: extConfig['beid'],
  //登录信息
  myInfo: {
    avatar: "",
    gender: 0,
    memberId: "",
    mobile: "",
    nickName: "",
    openId: "",
    token: "",
    unionId: ""
  },
  shopInfo: {}, //店铺信息
  userInfo: {}, //用户信息
  wxShopConfig: {}, //小程序信息
  customTabBar: extConfig['customTabBar'], //自定义tab
  isNew: 1, //默认是从未下过单的新用户
  globalData: {
    //主题色
    themeColor: '#A7D304',
    subColor: '#000000',
    btnColor: '#ffffff',
    //默认图片地址
    myTestImg: "https://ossweb-img.qq.com/images/lol/web201310/skin/big99008.jpg",
    //我的页
    myIndexTopBg: "https://yy-1254144956.cos.ap-guangzhou.myqcloud.com/images/2023/3/3/7e173275-114c-448c-9c1a-a3a8ee0cb30e.png",
    myIndexHeadImg1: "https://yy-1254144956.cos.ap-guangzhou.myqcloud.com/images/2023/3/3/438f0c99-0394-4e7d-a308-a639569eedf9.png",
    myIndexHeadImg2: "https://yy-1254144956.cos.ap-guangzhou.myqcloud.com/images/2023/3/3/f67b7d29-e921-4578-91b5-77d37d8b18f1.png",
    //订餐页
    myCouponBg1: "https://yy-1254144956.cos.ap-guangzhou.myqcloud.com/images/2023/3/6/88776579-e51d-485e-bea2-0294bdc45143.png",
    //会员码背景
    myPaymentCodeBg: "https://yy-1254144956.cos.ap-guangzhou.myqcloud.com/images/2023/3/25/737ca26c-5510-4082-8702-ba471ecf3c47.jpg",
    //无数据图片
    myNullData: "",
    //私人券背景
    myCouponBg: "https://yy-1254144956.cos.ap-guangzhou.myqcloud.com/images/2023/6/14/c9ddc627-f391-48cf-bc12-6e6563e96885.jpg",
    //存取酒图片
    myAccessWine: "https://yy-1254144956.cos.ap-guangzhou.myqcloud.com/images/2023/6/17/30bd5c9c-0677-44d2-a95e-cd3d3e70f655.jpg",
    //权益卡
    myEqCord1: "https://yy-1254144956.cos.ap-guangzhou.myqcloud.com/images/2023/6/21/a1a8f076-3b3e-43a9-994d-dc089071b314.jpg",
    myEqCord2: "https://yy-1254144956.cos.ap-guangzhou.myqcloud.com/images/2023/6/21/1ee6d176-b07a-4614-8966-862d828c781b.jpg",
    myEqCord3: "https://yy-1254144956.cos.ap-guangzhou.myqcloud.com/images/2023/6/21/e9a52118-8eb7-42f2-a17d-d52d1725bb93.jpg",
    myEqCord4: "https://yy-1254144956.cos.ap-guangzhou.myqcloud.com/images/2023/6/21/068f3b28-b22a-4c09-98a1-72f71847342d.jpg",
    myEqCord5: "https://yy-1254144956.cos.ap-guangzhou.myqcloud.com/images/2023/6/21/cbee1409-44cd-4061-afc9-c04530187942.jpg",
    //券包
    myCouponPackage: "https://yy-1254144956.cos.ap-guangzhou.myqcloud.com/images/2023/6/28/eea8fd2b-c23e-41d5-839d-43842e825cd4.png",
    tabBarSub: {
      "color": "#939393",
      "selectedColor": "#F2733E",
      "backgroundColor": "#ffffff",
      "borderStyle": "white",
      "position": "bottom",
      "selected": '0',
      "list": [{
          "text": "商户",
          "pagePath": "pages/index/index",
          "iconPath": "imgs/tabIcon/index.png",
          "selectedIconPath": "imgs/tabIcon/index_a.png"
        },
        {
          "text": "订单",
          "pagePath": "pages/order/order",
          "iconPath": "imgs/tabIcon/order.png",
          "selectedIconPath": "imgs/tabIcon/order_a.png"
        },
        {
          "text": "我的",
          "pagePath": "pages/my/my",
          "iconPath": "imgs/tabIcon/my.png",
          "selectedIconPath": "imgs/tabIcon/my_a.png"
        }
      ]
    },
    cartList: [], //购物车
    cartTotal: 0,
    isOpenCart: false, //是否打开购物车，再来一单操作
    setMealInfo: {}, //套餐商品缓存，选套餐
    goodsList: [], //商品列表，用于商品搜索
  },
  tabBarPath: [],
  tabBarParam: {},
  extConfig: {
    'isNew': extConfig['isNew']
  },
  onLaunch(options) {
    const that = this;
    wx.clearStorageSync("deskName")
    wx.clearStorageSync('deskCode')
    wx.clearStorageSync('deskId')
    wx.clearStorageSync('orderId')
    wx.clearStorageSync('paymentPriority')
    wx.clearStorageSync("orderType")
    wx.clearStorageSync("openCoverCharge")
    wx.clearStorageSync("peopleNumber")
    // wx.setStorageSync('addBtnFoods',true)
    console.log("onLaunch", options);
    //获取小程序状态条
    wx.getSystemInfo({
      success: e => {
        this.globalData.StatusBar = e.statusBarHeight;
        let capsule = wx.getMenuButtonBoundingClientRect();
        if (capsule) {
          this.globalData.Custom = capsule;
          this.globalData.CustomBar = e.statusBarHeight + capsule.height + (capsule.top - e.statusBarHeight) * 2;
        } else {
          this.globalData.CustomBar = e.statusBarHeight + 50;
        }
      }
    })

    //储存服务器地址,beid
    wx.setStorageSync('API_HOST', extConfig['apiHost']);

    //登录,不再此处登录，在每个页面判断
    if (this.token != "" || this.token != undefined) {
      var now = +new Date();
      var expiredTime = wx.getStorageSync('expiredTime');
      if (now != '' && expiredTime != '') {
        if (now - expiredTime >= 3 * 24 * 60 * 60 * 1000) {
          this.initLogin();
        }
      }
    }

    //保存tabBar列表
    let tabBarPath = [],
      tabBarParam = {};
    for (let key in extConfig['tabBarSetting']) {
      let item = extConfig['tabBarSetting'][key];
      if (key == 'index1') {
        this.HOMEPAGE_URL = '/' + item.pagePath;
      }

      tabBarPath.push('/' + item.pagePath);
      if (item.id) {
        tabBarParam[key] = item
      }
    }
    this.tabBarPath = tabBarPath;
    this.tabBarParam = tabBarParam;
    //更新
    const updateManager = wx.getUpdateManager()
    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
    })
    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success: function (res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })
    updateManager.onUpdateFailed(function () {
      // 新版本下载失败
    })
  },
  //初始化登录数据
  initLogin() {
    const that = this;
    return new Promise((resolve, reject) => {

      //商户beid，如果获取的beid和缓存的不一样，要重新获取用户信息
      var beid = wx.getStorageSync('beid');
      //获取token和过期时间,避免重复wx.login登录
      var token = wx.getStorageSync('token');
      var expiredTime = wx.getStorageSync('expiredTime');
      var myInfo = wx.getStorageSync('myInfo');
      var userInfo = wx.getStorageSync('userInfo');
      var shopInfo = wx.getStorageSync('shopInfo');
      var now = +new Date();
      //console.log(now);

      //为空需要重新登录，或者登录时间过期 3天则过期
      if (beid == "" || beid == undefined || beid != extConfig['beid'] || token == "" || token == undefined || now - expiredTime >= 3 * 24 * 60 * 60 * 1000) {
        // 登录 , 发送 res.code 到后台换取 openId, sessionKey, unionId
        wx.login({
          success: res => {
            console.log(res);
            wx.request({
              url: extConfig['apiHost'] + '/member/login',
              method: 'POST',
              data: {
                code: res.code
              },
              header: {
                'token_type': 'c_token',
                'beid': extConfig['beid'],
                'content-type': 'application/json'
              },
              success: function (res2) {
                console.log("登录信息", res2);

                if (res2.statusCode == 200) {
                  var data = res2.data.data;
                  //把 SessionId 和过期时间放在内存中的全局对象和本地缓存里边
                  that.token = data.token;
                  wx.setStorageSync('beid', extConfig['beid']);
                  wx.setStorageSync('token', data.token);
                  that.myInfo = data;
                  wx.setStorageSync('myInfo', data);
                  // 记录登录时间
                  var expiredTime = +new Date();
                  that.expiredTime = expiredTime
                  wx.setStorageSync('expiredTime', expiredTime)

                  //获取个人信息
                  wx.request({
                    url: extConfig['apiHost'] + '/api/vip/getUserBaseInfo',
                    method: 'GET',
                    data: {
                      memberId: that.myInfo.memberId,
                    },
                    header: {
                      'token_type': 'c_token',
                      'beid': extConfig['beid'],
                      'content-type': 'application/json',
                      'access-token': that.token,
                    },
                    success: function (res3) {
                      console.log("用户信息", res3.data.data);
                      if (res3.statusCode == 200) {
                        that.userInfo = res3.data.data;
                        wx.setStorageSync('userInfo', res3.data.data);
                      } else {
                        wx.showModal({
                          title: '提示',
                          content: res3.data,
                          showCancel: false
                        })
                      }

                    }
                  })

                  //获取商家门店信息
                  wx.request({
                    url: extConfig['apiHost'] + '/api/shop/getShopInfo',
                    method: 'GET',
                    data: {
                      beid: extConfig['beid'],
                    },
                    header: {
                      'token_type': 'c_token',
                      'content-type': 'application/json',
                      'access-token': that.token,
                    },
                    success: function (res3) {
                      console.log("门店信息", res3.data.data);
                      if (res3.statusCode == 200) {
                        that.shopInfo = res3.data.data;
                        //主题色
                        if (res3.data.data.colorType != '' && res3.data.data.colorType != null) {
                          that.globalData.themeColor = res3.data.data.colorType.themeColor;
                          that.globalData.subColor = res3.data.data.colorType.subColor;
                          that.globalData.btnColor = res3.data.data.colorType.btnColor;
                        }
                        wx.setStorageSync('shopInfo', res3.data.data);
                      } else {
                        wx.showModal({
                          title: '提示',
                          content: res3.data,
                          showCancel: false
                        })
                      }

                    }
                  })
                } else {
                  wx.showModal({
                    title: '提示',
                    content: res2.data,
                    showCancel: false
                  })
                }
                resolve(res2.data)
              },
              fail: err => {
                reject('error')
              }
            })
          }
        })
      } else {
        resolve()
        that.beid = beid;

        //这里是调试数据的时候使用，可用获取其他商户
        //喜茶
        //that.beid = 10000;
        //myInfo.memberId = 30137;
        //小肥男
        //that.beid = 10022;
        //myInfo.memberId = 49689;
        //随缘酒馆
        //that.beid = 10019;
        //myInfo.memberId = 54830;
        //哈皮妈妈
        //that.beid = 10080;
        //myInfo.memberId = 68135;

        that.token = token;
        that.expiredTime = expiredTime;
        that.myInfo = myInfo;
        that.userInfo = userInfo;
        that.shopInfo = shopInfo;
        //主题色
        if (shopInfo.colorType != '' && shopInfo.colorType != null) {
          that.globalData.themeColor = shopInfo.colorType.themeColor;
          that.globalData.subColor = shopInfo.colorType.subColor;
          that.globalData.btnColor = shopInfo.colorType.btnColor;
        }
      }

    })
  },

  onShow: function (options) {
    console.log('App Show')
    const updateManager = wx.getUpdateManager()
    updateManager.onCheckForUpdate(function (res) {
      console.log(res.hasUpdate, '更新') // 请求完新版本信息的回调 true说明有更新
    })
    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新检测', // 此处可自定义提示标题
        content: '检测到新版本，是否重启小程序？', // 此处可自定义提示消息内容
        success: function (res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })
    updateManager.onUpdateFailed(function () {
      // 新的版本下载失败
      wx.showModal({
        title: '更新提示',
        content: '新版本下载失败',
        showCancel: false
      })
    })
  },
  onHide() {

  },
  onError: function (msg) {},
})